package com.example.service.impl;

import com.example.mapper.ArticleMapper;
import com.example.pojo.AdminArticle;
import com.example.pojo.Article;
import com.example.pojo.ArticleList;
import com.example.pojo.PageBean;
import com.example.pojo.admin.SearchBean;
import com.example.service.ArticleService;
import com.example.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @Description TODO
 * @Author fantasy
 * @Date 2024/7/4 21:54
 **/

@Service
@Transactional
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Override
    public void add(Article article) {
        String img = article.getCoverImg();
        String string = getRandomString(10)+ Instant.now().getEpochSecond();
        File file;
        try {
            file = new File("D:\\studyJava\\ideaProject\\springboot-aliyun-start\\big-event\\uploadfile\\" + string + ".png");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(img.getBytes());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        article.setCoverImg(file.getName());
        if (article.getId() != null){
            articleMapper.update(article);
            return;
        }
        Map<String,Object> o = ThreadLocalUtil.get();
        Integer id = (Integer) o.get("id");
        article.setCreateUser(id);
        articleMapper.add(article);
    }
    private String getRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }
        return sb.toString();
    }
    /**
     * 根据分页参数和条件查询文章列表。
     *
     * @param pageNum 当前页码。
     * @param pageSize 每页显示的数量。
     * @param categoryId 分类ID，用于筛选特定分类的文章。
     * @param state 文章的状态，用于筛选特定状态的文章。
     * @return 返回分页后的文章列表信息。
     */
    @Override
    public PageBean<ArticleList> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        // 初始化分页信息对象
        PageBean<ArticleList> pageBean = new PageBean<>();
        // 开始分页，设置当前页码和每页显示的数量
        PageHelper.startPage(pageNum, pageSize);

        // 从线程本地存储中获取用户ID
        Map<String, Object> o = ThreadLocalUtil.get();
        Integer userId = (Integer) o.get("id");

        // 根据用户ID、分类ID和状态查询文章列表
        List<ArticleList> articleList = articleMapper.list(userId, categoryId, state);
        // 将查询结果转换为Page对象，以便获取分页信息
        Page<ArticleList> articlePage = (Page<ArticleList>) articleList;

        // 设置分页信息对象的总记录数和当前页的数据列表
        pageBean.setTotal((int) articlePage.getTotal());
        pageBean.setItems(articlePage.getResult());

        // 返回分页后的文章列表信息
        return pageBean;
    }

    @Override
    public List<ArticleList> getList(Integer categoryId, String state, Integer userId) {
        return articleMapper.getList(categoryId, state,userId);
    }

    @Override
    public AdminArticle getArticleById(Integer id) {
        AdminArticle article = articleMapper.getArticleById(id);
        String img = article.getCoverImg();
        File file = new File("D:\\studyJava\\ideaProject\\springboot-aliyun-start\\big-event\\uploadfile\\" + img);
        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] bytes = new byte[fis.available()];
            fis.read(bytes);
            article.setCoverImg(new String(bytes));
            fis.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return article;
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }

    @Override
    public List<AdminArticle> getAllList() {
        return articleMapper.getAllList();
    }

    @Override
    public void revoke(Integer id) {
        articleMapper.revoke(id);
    }

    @Override
    public List<AdminArticle> getLikeList(SearchBean searchBean) {
        return articleMapper.getLikeList(searchBean);
    }

}
